package pl.edu.agh.uddiProxy.client;

import java.util.ArrayList;
import java.util.Map;

import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.KeyboardListenerAdapter;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class DynamicQueryPanel extends QueryHorizontalPanel {
	private static final String[] LOGICAL_OPERATORS = new String[]{ "", "AND", "OR"};
	private static final String[] OPERATORS = new String[]{ "<", "<=", "=", ">=", ">" };
	private Map<String, Parameter> map;
	private ListBox operatorListBox;
	private Label unitLabel = new Label();
	
	public DynamicQueryPanel(Map<String, Parameter> map, ClickListener searchClickListener) {
		super(new ArrayList<String>(map.keySet()), LOGICAL_OPERATORS, searchClickListener);
		this.map = map;
		
		unitLabel.setWidth("20px");
		
		valueTextBox.addKeyboardListener(new KeyboardListenerAdapter() {
			public void onKeyPress(Widget sender, char keyCode, int modifiers) {
				if ((!Character.isDigit(keyCode))
						&& (keyCode != (char) KEY_TAB)
						&& (keyCode != (char) KEY_BACKSPACE)
						&& (keyCode != (char) KEY_DELETE)
						&& (keyCode != (char) KEY_ENTER)
						&& (keyCode != (char) KEY_HOME)
						&& (keyCode != (char) KEY_END)
						&& (keyCode != (char) KEY_LEFT)
						&& (keyCode != (char) KEY_UP)
						&& (keyCode != (char) KEY_RIGHT)
						&& (keyCode != (char) KEY_DOWN)) {
					((TextBox) sender).cancelKey();
				}
			}
		});

		nameListBox.addChangeListener(new ChangeListener() {
		
			public void onChange(Widget widget) {
				upadteUnitLabel();
			}
		});
		
		operatorListBox = new ListBox(false);
		for (String op : OPERATORS) {
			((ListBox) operatorListBox).addItem(op);
		}
		operatorPanel.add(operatorListBox);
		unitPanel.add(unitLabel);
		
		upadteUnitLabel();
	}
	
	private void upadteUnitLabel() {
		unitLabel.setText(DynamicQueryPanel.this.map.get(nameListBox.getItemText(nameListBox.getSelectedIndex())).getUnit());
	}

	public String getQuery() {
		if (valueTextBox.getText() != null && valueTextBox.getText().length() > 0) {
			return nameListBox.getItemText(nameListBox.getSelectedIndex()) + " " + 
				((ListBox) operatorListBox).getItemText(((ListBox) operatorListBox).getSelectedIndex()) + " " + 
					valueTextBox.getText() + " " + 
					logicalOperatorListBox.getItemText(logicalOperatorListBox.getSelectedIndex()) + " ";
		} else {
			return null;
		}
	}
}
